package com.zcy.util;

import java.io.BufferedInputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;

public class ClientSendUtil {

	private int port = 8821;
	private String ip = "192.168.253.105";
	private Socket socket = null;
	private DataOutputStream dataOutputStream;
	private String filePath = "E:\\sshe20121110.7z";
	private DataInputStream dataInputStream;

	void send() {
		try {
			socket = new Socket(ip, port);
			// 得到文件
			File fi = new File(filePath);
			// 将文件转化为文件输入流对象，放入到dataInputStream中,用于read文件
			dataInputStream = new DataInputStream(new BufferedInputStream(
					new FileInputStream(fi)));

			// 得到Socket的输出流对象，用于write写入数据
			dataOutputStream = new DataOutputStream(socket.getOutputStream());
			dataOutputStream.writeUTF(fi.getName());
			dataOutputStream.flush();
			dataOutputStream.writeLong(fi.length());
			dataOutputStream.flush();

			int bufferSize = 8192;
			byte[] buf = new byte[bufferSize];

			while (true) {
				int read = 0;
				if (dataInputStream != null) {
					// 开始读文件
					read = dataInputStream.read(buf);
				}
				if (read == -1) {
					break;
				}
				// 将读到的文件写入到dataOutputStream中
				dataOutputStream.write(buf, 0, read);
			}
			dataOutputStream.flush();
			// 注意关闭socket链接哦，不然客户端会等待server的数据过来，
			// 直到socket超时，导致数据不完整。
			dataInputStream.close();
			socket.close();
			System.out.println("文件传输完成\n");

		} catch (UnknownHostException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	public static void main(String[] args) {
		new ClientSendUtil().send();
	}
}
